<?php 
class session
{
 public $db;
 public $maxtime=600;
 function __construct()
 {
  session_set_save_handler(array(&$this, 'openSession'),
        array(&$this, 'closeSession'),
        array(&$this, 'readSession'),
        array(&$this, 'writeSession'),
        array(&$this, 'destroySession'),
        array(&$this, 'gcSession'));
  session_name('test');
  session_cache_limiter('private, must-revalidate');
  session_start();
 }

 function openSession()
 {
  global $db;
  $this->db=$db;
  //下面的代码是因为当在window环境下.老是不进行gcSession操作,所以干脆写到把清除失效session放到open里
  $time=time()-$this->maxtime;
  $this->db->del("delete from `session` where `timenow`<'$time'");
  return true;
 }
 function closeSession()
 {
  unset($this->db);
  return true;
 }
 function readSession($id)
 {
  if($session=$this->db->getfirst("select * from `session` where `id`='$id'")){
   return $session;
  }else{
   return '';
  }
 }
 function writeSession($id,$data)
 {
  $ip=getip();
  $time=time();
  if($session=$this->db->getfirst("select `id` from `session` where `id`='$id'")){
   $this->db->update("update `session` set `data`='$data',`ip`='$ip',`timenow`='$time' where `id`='$id' ");
   return true;
  }else{
   $this->db->insert("insert into `session` (`id`,`data`,`ip`,`time`,`timenow`) values ('$id','$data','$ip','$time','$time')");
   return true;
  }
 }
 function destroySession($id) { 
  if($this->db->del("delete from `session` where `id`='$id'")){
   return true; 
  }else{
   return false;
  }
 } 

 function gcSession($maxlifetime) 
 {
  $time=time()+$this->maxtime;
  if($this->db->del("delete from `session` where `nowtime`<'$time'")){
   return true; 
  }else{
   return false;
  }
 }
}

?>